import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import Layout from '@/layout'
import useUserStore from '@/store/modules/user'
import { dynamicRoutes } from "@/router"
NProgress.configure({ showSpinner: false });
const whiteList = ['/login', '/register','/cglogin'];
let isAddRouter = false;

router.beforeEach((to, from, next) => {
  NProgress.start()
  // 不需要登录,可访问
  if (whiteList.indexOf(to.path) !== -1) { // 在白名单 ，不需要token、
    return next();
  }
  // 如果有token
  if (useUserStore().token) {
    // 访问的页面是login直接放行到首页
    if (to.path === '/login') return next('/');
    else {
      // 这个只有在登录的时候执行
      if (!isAddRouter) {
        isAddRouter = true     
        // 添加路由
          router.addRoute({
            path: '/',
            component: Layout,
            redirect: '/index',
            children: dynamicRoutes(useUserStore().rolesName)
          })
        
        next({ ...to, replace: true });
      } else {
        next();
      }
    }

  } else {
    // 没有token如果访问的页面在白名单里直接放行,否则进入登陆页面
    if (whiteList.indexOf(to.path) !== -1) return next();
    else return next('/login');
  }

})

router.afterEach(() => {
  NProgress.done()
})
